package com.itcc.controller;

import com.itcc.entity.User;
import com.itcc.service.UserService;
import com.itcc.service.impl.UserServiceImpl;
import com.itcc.utils.Base64Utils;
import com.itcc.utils.Constants;
import com.itcc.utils.MD5Utils;
import com.itcc.utils.RandomUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@WebServlet("/user")

public class UserController extends BaseServlet {
    public String check(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        String username =request.getParameter("username");
        if(username==null){
            return Constants.HAS_USER;//不能注册
        }
        //调用业务逻辑判断用户名是否存在
        UserService userService=new UserServiceImpl();

        boolean b=userService.checkedUser(username);
        if(b){
            return Constants.HAS_USER;
        }
        return Constants.NOT_HAS_USER;

    }
    public String register(HttpServletRequest request,HttpServletResponse response){
        //获取用户信息
        Map<String,String[]> parameterMap=request.getParameterMap();
        User user=new User();

        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        user.setUstatus(Constants.USER_ACTIVE);//未激活
        user.setUrole(Constants.ROLE_CUSTOMER);//普通顾客
        user.setCode(RandomUtils.createActive());//随即设置激活码

        user.setUpassword(MD5Utils.md5(user.getUpassword()));//密码进行加密处理

        //进行注册
        UserService userService=new UserServiceImpl();
        try {
            userService.registerUser(user);

        }
        catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","注册失败");
            return Constants.FORWARD+"/register.jsp";
        }

        return Constants.FORWARD+"/registerSuccess.jsp";
    }

    public String active(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //获取激活码,此时已翻转成base64
        String c = request.getParameter("c");
        //base64翻转
        String code = Base64Utils.decode(c);

        UserService userService=new UserServiceImpl();
        int i=userService.activeUser(code);
        if(i==Constants.ACTIVE_FAIL){
            request.setAttribute("msg","未激活成功！");
        }
        else if(i==Constants.ACTIVE_SUCCESS){
            request.setAttribute("msg","成功激活，请登录！");
        }
        else{
            request.setAttribute("msg","已经激活！");
        }
        return Constants.FORWARD+"/message.jsp";
    }
    public String login(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        //从前端获得用户名，密码，验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String auto=request.getParameter("auto");

        //正确的验证码
        HttpSession session=request.getSession();
/*        String codestr=(String) session.getAttribute("code");

        //判断验证码是否正确
        if(codestr==null || !codestr.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码错误");
            return Constants.FORWARD+"/login.jsp";
        }*/

        //判断账户密码
        UserService userService=new UserServiceImpl();
        User user=userService.login(username,password);
        if(user==null){
            request.setAttribute("msg","账号或密码错误");
            return Constants.FORWARD+"/login.jsp";
        }
        if(user.getUstatus().equals(Constants.USER_NOT_ACTIVE)){
            request.setAttribute("msg","账号未激活");
            return Constants.FORWARD+"/login.jsp";
        }

        session.setAttribute("loginUser",user);

        //判断是否设置自动登录
        if(auto==null){
            //没有勾选
            Cookie cookie=new Cookie(Constants.AUTO_USER,"");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }else{
            //自动登录
            String content=username+Constants.FLAG+password;
            content=Base64Utils.encode(content);
            Cookie cookie=new Cookie(Constants.AUTO_USER,content);
            cookie.setPath("/");
            cookie.setMaxAge(14*24*60*60);
            response.addCookie(cookie);
        }
        return Constants.FORWARD+"/index.jsp";
    }

    //注销
    public String logOut(HttpServletRequest request,HttpServletResponse response){
            HttpSession session=request.getSession();
            session.removeAttribute("loginUser");

            Cookie cookie=new Cookie(Constants.AUTO_USER,"");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);

            request.setAttribute("msg","注销成功！");
            return Constants.FORWARD+"/login.jsp";
    }

    //显示所有用户
    public String manage(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");

        if (user == null || user.getUrole()==0) {
            request.setAttribute("msg", "您没有权限访问管理页面");
            return Constants.FORWARD + "/index.jsp"; // 重定向到错误页面
        }


        UserService userService = new UserServiceImpl();

        List<User> userList = userService.findAllUsers();

        request.setAttribute("userList",userList);

        return Constants.FORWARD + "/manageusers.jsp";
    }
}

